﻿// ***********************************************************************
// Assembly         : ELS
// Author           : linhvn
// Created          : 10-22-2012
//
// Last Modified By : linhvn
// Last Modified On : 10-22-2012
// ***********************************************************************
// <copyright file="ListUserForm.cs" company="">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.ComponentModel;

namespace ELS.User
{
    /// <summary>
    /// Class ListUserForm
    /// </summary>
    public partial class ListUserForm : MdiChildForm
    {
        /// <summary>
        /// The user controller
        /// </summary>
        UserController userController;

        Panel parentPanel;
        TextBox textBox;
        PictureBox pictureBox;

        // Page
        private int totalRecords = 0;
        private int pageSize = 15;
        private int pageCount = 0;
        private int currentPage = 1;

        public ListUserForm(TextBox textBox, PictureBox pictureBox, Panel pnlMainForm)
        {
            userController = new UserController();
            this.textBox = textBox;
            this.pictureBox = pictureBox;
            parentPanel = pnlMainForm;            
            InitializeComponent();

            // For Page view
            SetupPagingInformation();
            LoadDataGridViewPaging();
        }        

        /// <summary>
        /// Handles the TextChanged event of the promptedTxtSearchUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void promptedTxtSearchUser_TextChanged(object sender, EventArgs e)
        {
            string keyword = "";
            keyword = promptedTxtSearchUser.Text;

            SetupPagingInformation();
            LoadDataGridViewPaging();
        }

        /// <summary>
        /// Handles the Leave event of the promptedTxtSearchUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void promptedTxtSearchUser_Leave(object sender, EventArgs e)
        {
            bool isHasText = promptedTxtSearchUser.Text.Length > 0;
            if (!isHasText)
            {
                promptedTxtSearchUser.PromptText = UserCommon.SearchUser_PromoteText;
            }
        }

        /// <summary>
        /// Handles the CellClick event of the drgListUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="DataGridViewCellEventArgs" /> instance containing the event data.</param>
        private void drgListUser_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 1 && e.RowIndex >= 0)
            {
                string selectUsername = (drgListUser.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());

                foreach (Control ctl in parentPanel.Controls)
                {
                    ctl.Dispose();
                }

                AddEditUserForm addEditUserFrm = new AddEditUserForm(selectUsername, textBox, pictureBox, parentPanel, 2);
                addEditUserFrm.TopLevel = false;
                addEditUserFrm.Parent = parentPanel;
                addEditUserFrm.Show();
            }
        }

        /// <summary>
        /// Gets the list row select.
        /// </summary>
        /// <returns>List{System.String}.</returns>
        private List<string> GetListRowSelect()
        {
            List<string> rowsSelect = new List<string>();
            rowsSelect.Clear();
            foreach (DataGridViewRow row in drgListUser.Rows)
            {
                if (Convert.ToBoolean(row.Cells[0].Value) == true)
                {
                    rowsSelect.Add(row.Cells[1].Value.ToString());
                }
            }
            return rowsSelect;
        }


        /// <summary>
        /// Handles the Click event of the btnAddUser control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void btnAddUser_Click(object sender, EventArgs e)
        {
            
            try
            {
                foreach (Control ctl in parentPanel.Controls)
                {
                    ctl.Dispose();
                }

                AddEditUserForm addEditUserFrm = new AddEditUserForm(textBox, pictureBox, parentPanel);
                addEditUserFrm.TopLevel = false;
                addEditUserFrm.Parent = parentPanel;
                addEditUserFrm.Visible = true;
            }
            catch (Win32Exception ex)
            {
                return;
            }
        }

        /// <summary>
        /// Handles the Click event of the btnDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void btnDeleteUser_Click(object sender, EventArgs e)
        {
            bool isSelectedUser = GetListRowSelect().Count > 0;
            if (isSelectedUser)
            {
                DialogResult dialogConfirm = MessageBox.Show(UserCommon.DeleteUser_Message, UserCommon.DeleteUser_MessageBox_Title, MessageBoxButtons.YesNo);
                if (dialogConfirm == DialogResult.Yes)
                {
                    bool isDeleteSuccess = userController.DeleteSelectedUser(GetListRowSelect());
                    if (isDeleteSuccess)
                    {
                        UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.DeleteUser_Success,1);

                        // Reload content
                        SetupPagingInformation();
                        LoadDataGridViewPaging();
                    }
                    else
                    {
                        UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.DeleteUser_Fail, -1);                        
                    }
                }
                else if (dialogConfirm == DialogResult.No)
                {
                    return;
                }
            }
            else
            {
                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.DeleteUpdateUser_DoNotSelect, 0);                
            }
        }

        /// <summary>
        /// Handles the Click event of the btnEdit control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void btnEditUser_Click(object sender, EventArgs e)
        {
            bool isSelectedUser = GetListRowSelect().Count > 0;
            if (isSelectedUser)
            {
                bool isCanEdit = GetListRowSelect().Count == 1;
                if (isCanEdit)
                {
                    string selectUsername = GetListRowSelect()[0];
                    foreach (Control ctl in parentPanel.Controls)
                    {
                        ctl.Dispose();
                    }

                    AddEditUserForm addEditUserFrm = new AddEditUserForm(selectUsername, textBox, pictureBox, parentPanel, 1);
                    addEditUserFrm.TopLevel = false;
                    addEditUserFrm.Parent = parentPanel;
                    addEditUserFrm.Visible = true;
                }
                else
                {
                    UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.SelectUpdateUser_NotMulti, 0);
                }
            }
            else
            {
                UserCommon.NotifyOnMainForm(textBox, pictureBox, UserCommon.SelectUpdateUser_DoNotSelect, 0);
            }
        }

        // PAGING Implementation

        private void btnFirst_Click(object sender, EventArgs e)
        {
            this.goFirst();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            this.goPrevious(); 
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            this.goNext();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {            
            this.goLast();
        }

        private int CountAllUsers()
        {
            return userController.CountAllUsers();
        }

        private int CountAllUsersByKeyword(string keyword)
        {
            return userController.CountAllUsersByKeyword(keyword);
        }

        private void SetupPagingInformation()
        {
            // For Page view.
            if (promptedTxtSearchUser.Text != null && promptedTxtSearchUser.Text.Length > 0)
            {//search by keyword
                this.totalRecords = CountAllUsersByKeyword(promptedTxtSearchUser.Text);
            }
            else {// default load
                this.totalRecords = CountAllUsers();
            }
            
            this.pageCount = this.totalRecords / this.pageSize;
            // Adjust page count if the last page contains partial page.
            if (this.totalRecords % this.pageSize > 0)
                this.pageCount++;
            this.currentPage = 0;
        }

        /// <summary>
        /// Loads the data grid view.
        /// </summary>
        private void LoadDataGridViewPaging()
        {
            int intSkip = 0;
            intSkip = (this.currentPage * this.pageSize);

            drgListUser.AutoGenerateColumns = false;
            if (promptedTxtSearchUser.Text != null && promptedTxtSearchUser.Text.Length > 0)
            { //search by keyword
                drgListUser.DataSource = userController.GetAllUsersByKeywordPaging(promptedTxtSearchUser.Text, this.pageSize, intSkip);
            }
            else
            { // default load
                drgListUser.DataSource = userController.GetAllUsersPaging(this.pageSize, intSkip);
            }

            // Show Status
            this.lblStatus.Text = (this.currentPage + 1).ToString() + " / " + this.pageCount.ToString();
        }

        private void goFirst()
        {
            this.currentPage = 0;

            LoadDataGridViewPaging();
        }

        private void goPrevious()
        {
            if (this.currentPage == this.pageCount)
                this.currentPage = this.pageCount - 1;

            this.currentPage--;

            if (this.currentPage < 1)
                this.currentPage = 0;

            LoadDataGridViewPaging();
        }

        private void goNext()
        {
            this.currentPage++;

            if (this.currentPage > (this.pageCount - 1))
                this.currentPage = this.pageCount - 1;

            LoadDataGridViewPaging();
        }

        private void goLast()
        {
            this.currentPage = this.pageCount - 1;

            LoadDataGridViewPaging();
        }

        private void drgListUser_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            drgListUser.ClearSelection();
        }
    }
}